package com.web_bloks.widget.client;

//import java.util.Vector;
//import java.util.Iterator;

import com.web_bloks.system.client.Logger;

import com.google.gwt.dom.client.Document;
//import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Element;

import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.DOM;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;

import com.web_bloks.http.client.FormPost;
import com.web_bloks.widget.client.WidgetEx;

/**
 * FormWidget
 * - Configuration based on DOM mark-up
 * - Intercepts 'onClick' for the submit event
 * - Performs form submit
 * 
 * - [OPTIONAL] Sets a 'StatusIcon' widget
 * - [OPTIONAL] Sets the HTML of specified element with the POST response (IFF response == successful)
 * 
 * @author Jean-Lou Dupont
 *
 */
public class FormWidget 
	extends CollectionableWidget 
	implements WidgetEx, RequestCallback {

	final static String thisClass = "com.web_bloks.widget.FormWidget";
	
	String action = null;
	String submitid = null;
	String statusiconid = null;
	
	ButtonEx submitButton = null;

	FormPost fp = new FormPost();
	
	String id = null;
	
	String listeners = null;
	
	/*****************************************
	 * CONSTRUCTOR 
	 *****************************************/
	public FormWidget() {
		super();

		fp.setRequestCallback(this);
	}
	
	public FormWidget(Element parent, Element source) {
		super();
		fp.setRequestCallback(this);
		this.initFromDOMElement(parent, source);
	}
	/*****************************************
	 * WidgetEx 
	 *****************************************/
	
	/**
	 * Extracts attributes from the markup:
	 * - 'action'
	 * - submit button id
	 */
	public void initFromDOMElement(Element parent, Element source){
		
		this.setElement(source);
		String id = null;
		
		try {
			id = source.getAttribute("id");
			action = source.getAttribute("action");
			submitid = source.getAttribute("submitid");
			statusiconid = source.getAttribute("statusiconid");
			listeners = source.getAttribute("listeners");
			//Logger.logInfo(thisClass+".initFromDOMElement: action=" + action + ", submitid=" + submitid);
		}catch(Exception e){
			Logger.logWarn(thisClass+".initFromDOMElement: exception raised");
		}
		
		setId(id);
		
		Element submitButtonElement = null;
		
		if ( null != submitid ) {
			//Logger.logInfo(thisClass+".initFromDOMElement: submitd["+submitid+"]");
			
			Document doc = Document.get();
			
			submitButtonElement = doc.getElementById(submitid);
			
			if ( null != submitButtonElement ) {
				//Logger.logInfo(thisClass+".initFromDOMElement: FOUND submit button");
				DOM.setEventListener((com.google.gwt.user.client.Element)submitButtonElement, this);
				DOM.sinkEvents((com.google.gwt.user.client.Element)submitButtonElement, Event.ONCLICK);
			} else {
				Logger.logWarn(thisClass+".initFromDOMElement: submit element specified but not found");
			}
		}
		
	}
	
	/*****************************************
	 * DOM EVENT HANDLERS 
	 *****************************************/
	/**
	 * Used to capture events in cases where
	 * the widget is dynamically added to the DOM.
	 * Must use <code>DOM.setEventListener(el, object)</code>.
	 * 
	 */
	public void onBrowserEvent(Event evt) {
		
		Element target  = DOM.eventGetTarget(evt);
		String targetid = target.getAttribute("id");
		
		//Logger.logInfo(thisClass+".onBrowserEvent, submitid:" +submitid+", targetid:"+targetid);
		
		if (DOM.eventGetType(evt) == Event.ONCLICK)
			if ( submitid.compareTo(targetid) == 0 ) {
				doOnClick( target );
				return;
			}
	}
	/**
	 * Submits the form
	 * 
	 * @param el
	 */
	protected void doOnClick(Element el) {
		//Logger.logInfo(thisClass+".doOnClick");
		performPost();
	}

	/*========================================================
	 * REQUESTCALLBACK
	 ========================================================*/
	public void onError(Request request, java.lang.Throwable exception ) {
		Logger.logInfo( thisClass+".onError");
		//Window.alert("onError");
		executeChildCommands( "error", null );
	}
	
	public void onResponseReceived(Request request, Response response) {
		int code = response.getStatusCode();
		//Window.alert("onResponseReceived");
		Logger.logInfo( thisClass+".onResponseReceived, code=" + code);
		executeChildCommands( "ok", response );
	}
	
	/*****************************************
	 * HELPERS 
	 *****************************************/
	/**
	 * Finds child widgets and "executes" them.
	 * 
	 * This widget was certainly added to a 'widget collection'
	 * through the WidgetManager. 
	 */
	protected void executeChildCommands(String cond, Response response) {
		
		Logger.logInfo( thisClass+".executeChildCommands BEFORE");
		WidgetManager wm = WidgetManager.create( );
		
		wm.executeListeners(this, listeners, cond, response);
		Logger.logInfo( thisClass+".executeChildCommands AFTER");
	}
	
	protected boolean performPost() {

		if (fp.isPending())
			return false;
	
		if ( action == null ) {
			throw new RuntimeException( thisClass+ ".performPost: action can't be null");
		}
		
		try {
			fp.post( action, this.getElement() );
		} catch(Exception e) {
			Logger.logError(thisClass+".performPost: exception raised, msg="+e.getMessage());
			return false;
		}
		
		return true;
	}
	
	
}//END
